package com.market.service.wx.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.market.bean.*;
import com.market.bean.bo.wx.WxOrderCommentBo;
import com.market.bean.common.CommonData;
import com.market.bean.vo.wx.HandleOptionEntity;
import com.market.bean.vo.wx.WxOrderDetailVo;
import com.market.bean.vo.wx.WxOrderListVo;
import com.market.mapper.*;
import com.market.service.wx.WxOrderService;
import com.market.bean.bo.wx.WxOrderSubmitBo;
import com.market.bean.vo.wx.WxOrderSubmitVo;
import com.market.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Transactional
@Service
public class WxOrderServiceImpl implements WxOrderService {
    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Override
    public CommonData<WxOrderListVo> list(Short showType, Integer page, Integer limit, Integer userId) {
        if (page != null) {
            PageHelper.startPage(page, limit);
        } else {
            PageHelper.startPage(0, 0, true, true, true);
        }
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }

        if (showType != null) {
            if (showType == 1) {
                ArrayList<Short> shorts = new ArrayList<>();
                shorts.add((short) 101);
                shorts.add((short) 102);
                shorts.add((short) 103);
                criteria.andOrderStatusIn(shorts);
            } else if (showType == 2) {
                ArrayList<Short> shorts = new ArrayList<>();
                shorts.add((short) 201);
                shorts.add((short) 202);
                shorts.add((short) 203);
                criteria.andOrderStatusIn(shorts);
            } else if (showType == 3) {
                ArrayList<Short> shorts = new ArrayList<>();
                shorts.add((short) 301);
                criteria.andOrderStatusIn(shorts);
            } else if (showType == 4) {
                ArrayList<Short> shorts = new ArrayList<>();
                shorts.add((short) 401);
                shorts.add((short) 402);
                criteria.andOrderStatusIn(shorts);
            }
        }
        criteria.andDeletedEqualTo(false);
        marketOrderExample.setOrderByClause("add_time" + " " + "desc");
        // 查询订单
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        List<WxOrderListVo> wxOrderListVoList = new LinkedList<>();
        for (MarketOrder marketOrder : marketOrders) {
            WxOrderListVo wxOrderListVo = new WxOrderListVo();
            wxOrderListVo.setId(marketOrder.getId());
            wxOrderListVo.setOrderSn(marketOrder.getOrderSn());
            wxOrderListVo.setOrderStatusText(getOrderStatusText(marketOrder.getOrderStatus()));
            wxOrderListVo.setActualPrice(marketOrder.getActualPrice());
            wxOrderListVo.setAftersaleStatus(marketOrder.getAftersaleStatus());
            wxOrderListVo.setGroupin(false);

            MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria goodsExampleCriteria = marketOrderGoodsExample.createCriteria();
            if (marketOrder.getId() != null) {
                goodsExampleCriteria.andOrderIdEqualTo(marketOrder.getId());
            }
            criteria.andDeletedEqualTo(false);
            // 查询商品
            List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
            List<WxOrderListVo.GoodsListEntity> goodsListEntities = marketOrderGoods.stream()
                    .map(result -> new WxOrderListVo().new GoodsListEntity(result.getId(), result.getGoodsName(),
                            result.getNumber(), result.getPrice(), result.getPicUrl(), result.getSpecifications()))
                    .collect(Collectors.toList());
            wxOrderListVo.setGoodsList(goodsListEntities);
            wxOrderListVo.setHandleOption(getHandleOptionEntity(marketOrder.getOrderStatus()));
            wxOrderListVoList.add(wxOrderListVo);
        }
        PageInfo<WxOrderListVo> pageInfo = new PageInfo<>(wxOrderListVoList);
        return CommonData.data(pageInfo);
    }

    private String getOrderStatusText(Short orderStatus) {
        switch (orderStatus) {
            case 101:
                return "未付款";
            case 102:
                return "用户取消";
            case 103:
                return "系统取消";
            case 201:
                return "已付款";
            case 202:
                return "申请退款";
            case 203:
                return "已退款";
            case 301:
                return "已发货";
            case 401:
                return "用户收货";
            case 402:
                return "系统收货";
        }
        return "异常状态";
    }

    private HandleOptionEntity getHandleOptionEntity(Short orderStatus) {
        HandleOptionEntity handleOptionEntity = new HandleOptionEntity();
        switch (orderStatus) {
            case 101:
                handleOptionEntity.setPay(true);
                handleOptionEntity.setCancel(true);
                break;
            case 102:
                handleOptionEntity.setDelete(true);
                break;
            case 103:
                handleOptionEntity.setDelete(true);
                break;
            case 201:
                handleOptionEntity.setRefund(true);
                break;
            case 202:
                handleOptionEntity.setRefund(true);
                break;
            case 203:
                handleOptionEntity.setDelete(true);
                break;
            case 301:
                handleOptionEntity.setConfirm(true);
                break;
            case 401:
                handleOptionEntity.setDelete(true);
                handleOptionEntity.setAftersale(true);
                handleOptionEntity.setRebuy(true);
                handleOptionEntity.setComment(true);
                break;
            case 402:
                handleOptionEntity.setDelete(true);
                handleOptionEntity.setAftersale(true);
                handleOptionEntity.setRebuy(true);
                handleOptionEntity.setComment(true);
                break;
        }
        return handleOptionEntity;
    }

    @Override
    public WxOrderDetailVo detail(Integer orderId) {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        // 如果不为空，则拼接条件
        if (orderId != null) {
            criteria.andIdEqualTo(orderId);
        }
        criteria.andDeletedEqualTo(false);

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        WxOrderDetailVo.OrderInfoEntity orderInfo = new WxOrderDetailVo().new OrderInfoEntity();
        orderInfo.setId(marketOrder.getId());
        orderInfo.setOrderSn(marketOrder.getOrderSn());
        orderInfo.setOrderStatusText(marketOrder.getOrderSn());
        orderInfo.setGoodsPrice(marketOrder.getGoodsPrice());
        orderInfo.setActualPrice(marketOrder.getActualPrice());
        orderInfo.setCouponPrice(marketOrder.getCouponPrice());
        orderInfo.setFreightPrice(marketOrder.getFreightPrice());
        orderInfo.setAftersaleStatus(marketOrder.getAftersaleStatus());
        orderInfo.setMobile(marketOrder.getMobile());
        orderInfo.setAddress(marketOrder.getAddress());
        orderInfo.setConsignee(marketOrder.getConsignee());
        orderInfo.setAddTime(marketOrder.getAddTime());
        orderInfo.setHandleOption(getHandleOptionEntity(marketOrder.getOrderStatus()));

        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria goodsExampleCriteria = marketOrderGoodsExample.createCriteria();
        // 如果不为空，则拼接条件
        if (orderId != null) {
            goodsExampleCriteria.andOrderIdEqualTo(orderId);
        }
        goodsExampleCriteria.andDeletedEqualTo(false);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        List<WxOrderDetailVo.OrderGoodsEntity> orderGoods = marketOrderGoods.stream()
                .map(result -> new WxOrderDetailVo().new OrderGoodsEntity(
                        result.getId(), result.getOrderId(), result.getGoodsId(), result.getGoodsName(), result.getGoodsSn(),
                        result.getNumber(), result.getPrice(), result.getProductId(), result.getPicUrl(), result.getSpecifications(),
                        result.getComment(), result.getAddTime(), result.getUpdateTime(), result.getDeleted()
                ))
                .collect(Collectors.toList());

        WxOrderDetailVo wxOrderDetailVo = new WxOrderDetailVo();
        // TODO
        wxOrderDetailVo.setExpressInfo(null);
        wxOrderDetailVo.setOrderInfo(orderInfo);
        wxOrderDetailVo.setOrderGoods(orderGoods);

        return wxOrderDetailVo;
    }

    // TODO 提取方法
    @Override
    public WxOrderSubmitVo submit(WxOrderSubmitBo wxOrderSubmitBo) {
        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(wxOrderSubmitBo.getCartId());
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(wxOrderSubmitBo.getCouponId());
        MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(wxOrderSubmitBo.getUserCouponId());
        MarketGrouponRules marketGrouponRules = marketGrouponRulesMapper.selectByPrimaryKey(wxOrderSubmitBo.getGrouponRulesId());
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(wxOrderSubmitBo.getAddressId());

        // 创建订单表对象
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setUserId(marketCart.getUserId());
        marketOrder.setOrderSn(RandomUtil.newOrderSn());
        marketOrder.setOrderStatus((short) 101);
        marketOrder.setAftersaleStatus((short) 0);
        marketOrder.setConsignee(marketAddress.getName());
        marketOrder.setMobile(marketAddress.getTel());
        marketOrder.setAddress(marketAddress.getAddressDetail());
        marketOrder.setMessage(wxOrderSubmitBo.getMessage());
        // 计算总价格原价
        BigDecimal goodsPrice = marketCart.getPrice().multiply(BigDecimal.valueOf(marketCart.getNumber()));
        marketOrder.setGoodsPrice(goodsPrice);
        // 配送费用 TODO
        marketOrder.setFreightPrice(BigDecimal.valueOf(0));
        // 满减优惠 TODO CouponUser.getStatus
        if (goodsPrice.compareTo(marketCoupon.getMin()) != -1 && marketCouponUser.getStatus() == 0) {
            marketOrder.setCouponPrice(marketCoupon.getDiscount());
        }
        // 积分优惠 TODO
        marketOrder.setIntegralPrice(BigDecimal.valueOf(0));
        // 团购优惠
        if (marketGrouponRules != null) {
            marketOrder.setGrouponPrice(marketGrouponRules.getDiscount());
        } else {
            marketOrder.setGrouponPrice(BigDecimal.valueOf(0));
        }
        marketOrder.setOrderPrice(goodsPrice.subtract(marketOrder.getFreightPrice()).add(marketOrder.getCouponPrice()));
        marketOrder.setActualPrice(goodsPrice.subtract(marketOrder.getFreightPrice()).add(marketOrder.getCouponPrice()));
        // TODO 待评价订单商品数量
        marketOrder.setComments((short) 0);
        marketOrder.setAddTime(new Date());
        marketOrder.setUpdateTime(new Date());
        marketOrder.setDeleted(false);
        marketOrderMapper.insert(marketOrder);

        // 创建订单关联商品对象 TODO 循环创建所有对象
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        marketOrderGoods.setOrderId(marketOrder.getId());
        marketOrderGoods.setGoodsId(marketCart.getGoodsId());
        marketOrderGoods.setGoodsName(marketCart.getGoodsName());
        marketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
        marketOrderGoods.setProductId(marketCart.getProductId());
        marketOrderGoods.setNumber(marketCart.getNumber());
        marketOrderGoods.setPrice(marketCart.getPrice());
        marketOrderGoods.setSpecifications(marketCart.getSpecifications());
        marketOrderGoods.setPicUrl(marketCart.getPicUrl());
        // 订单商品评论，如果是-1，则超期不能评价；如果是0，则可以评价；如果其他值，则是comment表里面的评论ID。
        marketOrderGoods.setComment(0);
        marketOrderGoods.setAddTime(new Date());
        marketOrderGoods.setUpdateTime(new Date());
        marketOrderGoods.setDeleted(false);
        marketOrderGoodsMapper.insert(marketOrderGoods);

        // 创建Vo返回对象
        WxOrderSubmitVo wxOrderSubmitVo = new WxOrderSubmitVo();
        wxOrderSubmitVo.setGrouponLinkId(wxOrderSubmitBo.getGrouponLinkId());
        wxOrderSubmitVo.setOrderId(marketOrder.getId());
        return wxOrderSubmitVo;
    }

    @Override
    public void cancel(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short) 102);
        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKey(marketOrder);
    }

    @Override
    public int prepay(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short) 201);
        marketOrder.setPayId("已付款");
        marketOrder.setPayTime(new Date());
        marketOrder.setUpdateTime(new Date());
        int code;
        try {
            marketOrderMapper.updateByPrimaryKey(marketOrder);
            // TODO 魔法值
            code = 200;
        } catch (Exception e) {
            code = 404;
        }
        return code;
    }

    @Override
    public void refund(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short) 202);
        marketOrder.setRefundAmount(marketOrder.getActualPrice());
        marketOrder.setRefundType("微信退款");
        marketOrder.setRefundContent("退款成功");
        marketOrder.setRefundTime(new Date());
        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKey(marketOrder);
    }

    @Override
    public void confirm(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setOrderStatus((short) 401);
        marketOrder.setConfirmTime(new Date());
        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKey(marketOrder);
    }

    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        // 如果不为空，则拼接条件
        if (orderId != null) {
            criteria.andOrderIdEqualTo(orderId);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andDeletedEqualTo(false);

        List<MarketOrderGoods> marketOrderGoodsList = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        return marketOrderGoodsList.get(0);
    }

    @Override
    public MarketComment comment(WxOrderCommentBo wxOrderCommentBo) {
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByPrimaryKey(wxOrderCommentBo.getOrderGoodsId());

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(marketOrderGoods.getOrderId());
        marketOrder.setComments((short) (marketOrder.getComments() - 1));
        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKey(marketOrder);

        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(marketOrderGoods.getGoodsId());
        marketComment.setType((byte) 0);
        marketComment.setContent(wxOrderCommentBo.getContent());
        marketComment.setUserId(marketOrder.getUserId());
        marketComment.setHasPicture(wxOrderCommentBo.isHasPicture());
        marketComment.setPicUrls(wxOrderCommentBo.getPicUrls());
        // marketComment.setPicUrls(Arrays.asList(wxOrderCommentBo.getPicUrls()).tos);
        marketComment.setStar((short) wxOrderCommentBo.getStar());
        marketComment.setAddTime(new Date());
        marketComment.setUpdateTime(new Date());
        marketComment.setDeleted(false);
        marketCommentMapper.insert(marketComment);

        marketOrderGoods.setComment(marketComment.getId());
        marketOrderGoods.setUpdateTime(new Date());
        marketOrderGoodsMapper.updateByPrimaryKey(marketOrderGoods);
        return marketComment;
    }

    @Override
    public void delete(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setDeleted(true);
        marketOrder.setEndTime(new Date());
        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKey(marketOrder);
    }
}
